﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using CUWo.App.CustomControl;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CUWo.App.WoControls
{
    public partial class WoTrackBarChart : UserControl
    {
        public WoTrackBarChart()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 首页公告信息
        /// </summary>
        public void BindTrackCurrent()
        {
            string mobileNumber = string.Empty;
            RomInfo romInfo = RomHelper.GetRomInfo();
            if (romInfo != null)
            {
                mobileNumber = romInfo.Mobile;
            }
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show("未登录，请登录！", MessageToastLevel.Warn);
                return;
            }
            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.TrackCurrent().GetUrl(mobileNumber);
            LogHelper.LogInfo(requestUrl);
            //
            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageTrackCurrent jsonResult = JSONHelper.Deserialize<JsonResultMessageTrackCurrent>(decryptStringResult);
                            if (jsonResult != null)
                            {
                                if (jsonResult.Msg != null)
                                {
                                    if (jsonResult.Msg.MessageErrors != null && jsonResult.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (jsonResult.Msg.MessageWarns != null && jsonResult.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (jsonResult.Msg.MessagePrompts != null && jsonResult.Msg.MessagePrompts.Count > 0)
                                        {
                                            this.BindFlowInf(jsonResult.FlowInf);
                                        }
                                    }
                                }
                            }

                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }


        private string FormatDateTimeString(string datetime)
        {
            if (string.IsNullOrWhiteSpace(datetime))
                return "未知";
            if (datetime.Length != 8)
                return datetime;
            return string.Concat(datetime.Substring(0, 4), "-", datetime.Substring(4, 2), "-", datetime.Substring(6, 2));
        }


        private const double BARCHART_WIDTH = 456;

        private void BindFlowInf(FlowInf item)
        {
            if (item == null)
            {
                return;
            }

            this.txtTrackPackageDateTime.Text = string.Concat(FormatDateTimeString(item.DetailStartDate), "~", FormatDateTimeString(item.DetailEndDate));
            this.txtTrackPackageName.Text = string.IsNullOrWhiteSpace(item.ProductName) ? "套餐名称未知" : item.ProductName;
            double totalFlow = 0, usedFlow = 0;
            double.TryParse(item.TotalFlow, out totalFlow);
            double.TryParse(item.UsedFlow, out usedFlow);
            this.txtTrackPackageDetail.Text = string.Format("套餐总量 {0}MB，剩余 {1}MB未使用.", totalFlow, totalFlow - usedFlow);
            if (totalFlow <= 0)
            {
                this.borderUsed.Background = new SolidColorBrush(Helper.HexToColor("#ff828282"));
                return;
            }

            this.borderUsed.Background = new SolidColorBrush(Helper.HexToColor("#ff828282"));
            if (usedFlow <= 0)
            {
                this.borderUnused.Width = BARCHART_WIDTH;
                this.borderUsed.Width = 0;
                this.borderUnused.Background = new SolidColorBrush(Helper.HexToColor("#ff91c833"));
            }
            else
            {
                double percentValue = (usedFlow / totalFlow) * 1.0000;

                if (percentValue <= 0.25)
                {                    
                    this.borderUnused.Background = new SolidColorBrush(Helper.HexToColor("#ff91c833"));
                }
                else if (percentValue <= 0.75)
                {
                    this.borderUnused.Background = new SolidColorBrush(Helper.HexToColor("#fffa8600"));
                }
                else if (percentValue <= 0.9)
                {
                    this.borderUnused.Background = new SolidColorBrush(Helper.HexToColor("#ffdd0000"));
                }

                this.borderUnused.Width = BARCHART_WIDTH * (1 - percentValue);
                this.borderUnused.Margin = new Thickness((BARCHART_WIDTH - this.borderUnused.Width), 0, 0, 0);
            }
        }



    }
}
